﻿using Abp.Dependency;
using Abp.Web.Models;
using GN.Pay.Application.GatewayApp;
using GN.Pay.Application.GatewayApp.Dto.Input;
using GN.Pay.Application.GatewayApp.Dto.Output;
using GN.Pay.Core.Services;
using GN.Pay.GatewayWeb.Controllers.PayRoute;
using GN.Pay.GatewayWeb.Models;
using GN.Pay.TradeChannel;
using System;
using System.Web.Mvc;

namespace GN.Pay.GatewayWeb.Controllers
{
    /// <summary>
    /// 收银台
    /// </summary>
    public class CashieController : PayControllerBase
    {
        private readonly ITradeApplyAppService service;
        private readonly IIocManager iocManager;

        public CashieController(ITradeApplyAppService service, IIocManager iocManager)
        {
            this.service = service;
            this.iocManager = iocManager;
        }

        /// <summary>
        /// 支付申请
        /// </summary>
        /// <param name="applyId">申请号</param>
        /// <returns></returns>
        public ActionResult Pay(string applyId)
        {
            if (string.IsNullOrWhiteSpace(applyId))
            {
                return this.ErrorView("出错",
                   "付款申请出错",
                   "未指定付款申请号");
            }
            try
            {
                var outDto = service.CashiePayApply(new CashiePayApplyInput() { ApplyId = applyId, ChannelType = ChannelType.Web });
                if (outDto == null)
                {
                    return this.ErrorView("出错",
                        "付款申请出错",
                        "支付申请号:" + applyId + " 可能无效、已支付过或支付期限过期");
                }
                return View(outDto);
            }
            catch (Exception err)
            {
                return this.ErrorView("出错",
                   "付款申请出错",
                   err.Message);
            }
        }

        /// <summary>
        /// 会员银行卡绑定申请
        /// </summary>
        /// <param name="input">输入</param>
        [HttpPost]
        public JsonResult MemberBankCardBindApply(BankCardBindPayApplyInput input)
        {
            if (input == null)
            {
                return this.Json(new AjaxResponse(new ErrorInfo(0, "输出参数无效")));
            }
            input.TrimString();
            try
            {
                var service = iocManager.Resolve<IBankCardAppService>();
                var result = service.MerchantMemberBankCardBindApply(input);
                return this.Json(new AjaxResponse(result));
            }
            catch (Exception err)
            {
                return this.Json(new AjaxResponse(new ErrorInfo(0, err.Message)));
            }
        }

        /// <summary>
        /// 会员银行卡绑定
        /// </summary>
        /// <param name="input">输入</param>
        [HttpPost]
        public JsonResult MemberBankCardBind(MerchantMemberBankCardBindInput input)
        {
            if (input == null)
            {
                return this.Json(new AjaxResponse(new ErrorInfo(0, "输出参数无效")));
            }
            try
            {
                var service = iocManager.Resolve<IBankCardAppService>();
                var result = service.MerchantMemberBankCardBind(input);
                return this.Json(new AjaxResponse(result));
            }
            catch (Exception err)
            {
                return this.Json(new AjaxResponse(new ErrorInfo(0, err.Message)));
            }
        }

        /// <summary>
        /// 短信付款
        /// </summary>
        /// <param name="input">输入</param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult SmsPay(SmsPayInput input)
        {
            if (input == null)
            {
                return this.Json(new AjaxResponse(new ErrorInfo(0, "输出参数无效")));
            }
            try
            {
                var result = service.SmsPay(input);
                return this.Json(new AjaxResponse(result));
            }
            catch (Exception err)
            {
                return this.Json(new AjaxResponse(new ErrorInfo(0, err.Message)));
            }
        }

        /// <summary>
        /// 付款通道
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public ActionResult PayChannel(PayChannelModel input)
        {
            if (input == null)
            {
                return this.ErrorView("出错", "付款出错", "申请信息为null");
            }
            if (string.IsNullOrWhiteSpace(input.ApplyId))
            {
                return this.ErrorView("出错", "付款出错", "申请号为空");
            }
            if (string.IsNullOrWhiteSpace(input.ChannelId))
            {
                return this.ErrorView("出错", "付款出错", "支付通道为空");
            }
            if (!PayRouteInstaller.Instance.IsRegisterRoute(input.ChannelId))
            {
                return this.ErrorView("出错", "付款出错", "不支持支付通道：" + input.ChannelId);
            }
            try
            {
                var route = PayRouteInstaller.Instance.Resolve(iocManager, input.ChannelId);
                return route.ViewResult(input, this.View);
            }
            catch (Exception err)
            {
                this.Logger.Error("付款出错", err);
                return this.ErrorView("出错", "付款出错", err.Message);
            }
        }

        /// <summary>
        /// 支付跳转
        /// </summary>
        /// <param name="tradeNo">交易号</param>
        /// <returns></returns>
        public ActionResult PayRedirectResult(string tradeNo)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(tradeNo))
                {
                    return this.ErrorView("提示", "交易提示", "交易号为空");
                }
                var service = iocManager.Resolve<ITradeCacheService>();
                var notify = service.GetPayReturnNotify(tradeNo);
                if (notify == null)
                {
                    return this.ErrorView();
                }
                if (string.IsNullOrWhiteSpace(notify.ReturnUrl))
                {
                    return this.ErrorView("提示", "交易提示", "未查询到相关数据，若已付款，请自行返回原站查询订单信息");
                }
                var notifyService = iocManager.Resolve<ITradeNotifyService>();
                var dic = notifyService.Sign(notify);
                string url;
                if (notify.ReturnUrl.Contains("?"))
                {
                    url = notify.ReturnUrl + "&" + dic.UrlLinkString();
                }
                else
                {
                    url = notify.ReturnUrl + "?" + dic.UrlLinkString();
                }
                return new RedirectResult(url);
            }
            catch (Exception err)
            {
                this.Logger.Error(err.Message, err);
                return this.ErrorView("提示", "交易提示", "出现未知异常");
            }
        }
    }
}